package com.wt.springsamples.es.client;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import co.elastic.clients.elasticsearch.indices.GetIndexResponse;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;

import javax.net.ssl.SSLContext;
import java.io.File;

public class Es8CaConnectTest {
    private static final Log logger = LogFactory.getLog(Es8CaConnectTest.class);

    public static void main(String[] args) throws Exception {

        File certFile = new File("D:/java-env/elk/elasticsearch-8.14.2/config/certs/http_ca.crt");

        SSLContext sslContext = TransportUtils.sslContextFromHttpCaCrt(certFile);

        BasicCredentialsProvider credsProv = new BasicCredentialsProvider();
        credsProv.setCredentials(
                AuthScope.ANY, new UsernamePasswordCredentials("elastic", "eIu7*gbSUDjSdHQQyTyc")
        );

        RestClient restClient = RestClient
                .builder(new HttpHost("localhost", 9200, "https"))
                .setHttpClientConfigCallback(hc -> hc
                        .setSSLContext(sslContext)
                        .setDefaultCredentialsProvider(credsProv)
                )
                .build();

        Request request = new Request("GET","/");
        Response response = restClient.performRequest(request);
        System.out.println(response);

        // Create the transport and the API client
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient esClient = new ElasticsearchClient(transport);

//        client.indices().create(c -> c
//                .index("posts")
//        );
        GetIndexResponse getIndexResponse = esClient.indices().get(
                builder -> builder.index("products")
        );

        logger.info("============getIndexResponse===》》》 " + getIndexResponse.result());

        IndexResponse indexResponse = esClient.index(i -> i
                .index("products")
                .document(new Product())
        );

        logger.info("Indexed with version " + indexResponse.version());

        restClient.close();
    }
}
